package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
@Transactional
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private CartService cartService;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    //提交订单
    @Override
    public void save(Orders orders) {
        //1 获取当前用户
        User user = UserHolder.get();

        //感觉这一步是不用判断的//2 查询当前用户的购物车，如果为空直接返回错误提示
        List<Cart> cartList = cartService.findList();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车数据为空，无法下单");
        }

        //2 根据提交的addressId 查询用户的收货地址信息，如果不存在，直接返回错误提示
        Address address = addressMapper.selectById(orders.getAddressId());
        if (address == null){
            throw new CustomException("没有收货地址，无法下单");
        }

        //3 组装订单详情数据，保存订单详情表
        //3-1 先确定下订单的主键
        long orderId = IdWorker.getId();//mybatis plus提供的雪花算法的写法

        //3-2 组装订单详情
        BigDecimal amount = new BigDecimal(0);//初始化金额为0
        for (Cart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();//订单详情
            orderDetail.setName(cart.getName());//设置菜品名称
            orderDetail.setOrderId(orderId);//设置提前生成的id
            orderDetail.setDishId(cart.getDishId());//设置菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//设置套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor());//设置菜品
            orderDetail.setNumber(cart.getNumber());//设置菜品数量
            orderDetail.setAmount(cart.getAmount());//设置金额
            orderDetail.setImage(cart.getImage());//设置图片
            //叠加金额 amount = amout + cart.getAmount() * cart.getNumber
            amount = amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
            orderDetailMapper.insert(orderDetail);

        }
        //4 组装订单数据 保存订单表
        orders.setId(orderId);//这个订单的主键是我们自己定义的
        orders.setNumber(String.valueOf(orderId));//订单号 自己定义
        orders.setStatus(1);//1 表示待付款
        orders.setUserId(user.getId());//下单用用户id
        orders.setOrderTime(new Date());//下单时间
        orders.setCheckoutTime(new Date());//todo 支付时间，应该是支付的时候才来填这个值
        orders.setAmount(amount);//订单总金额 = 所有订单项金额之和
        orders.setUserName(user.getName());
        orders.setPhone(address.getPhone());//地址中得到联系电话

        orders.setAddress(address.getDetail());//联系地址
        orders.setConsignee(address.getConsignee());//地址中取得联系人名称
        ordersMapper.insert(orders);

        //注意 企业大多数的情况下 先一个表 再多个表 因为多个表会用到一个表的主键

        //5 清空购物车
        cartService.clean();
    }

    @Override
    public Page<Orders> findByPage(Long number, Integer pageNum, Integer pageSize, String beginTime, String endTime) {
        Page<Orders> page = new Page<>(pageNum,pageSize);

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(number != null,Orders::getNumber,number);
        if (beginTime == null && endTime == null){
            page = ordersMapper.selectPage(page,wrapper);
            return page;
        }else{
            LambdaQueryWrapper<Orders> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.like(number != null,Orders::getNumber,number).ge(beginTime!= null,Orders::getOrderTime,beginTime)
            .lt(endTime!=null,Orders::getOrderTime,endTime);
            page = ordersMapper.selectPage(page,wrapper1);
            return page;
        }

    }


    @Override
    public Page<Orders> findAll(Integer pageNum, Integer pageSize) {
        Page<Orders> page = new Page<>(pageNum,pageSize);

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,UserHolder.get().getId());

        wrapper.orderByDesc(Orders::getOrderTime);
        ordersMapper.selectPage(page,wrapper);

        List<Orders> orders = page.getRecords();
        if (CollectionUtil.isNotEmpty(orders)) {
            for (Orders order : orders) {


                LambdaQueryWrapper<OrderDetail> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(OrderDetail::getOrderId,order.getId());
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper2);

                order.setOrderDetails(orderDetails);

            }
        }

        return page;
    }
}
